<?php
defined('IN_PHPCMS') or exit('No permission resources.');
class index {
	function __construct() {
		pc_base::load_app_func('global');
		$this->order = pc_base::load_model('order_model');//投票标题
		$this->username = param::get_cookie('_username');
		$this->userid = param::get_cookie('_userid');
		$this->ip = ip();
		
		$siteid = isset($_GET['siteid']) ? intval($_GET['siteid']) : get_siteid();
  		define("SITEID",$siteid);
  		
  		if (!$this->userid) {
  			$this->output(false, '您没有权限进行此操作，请您先登录!', APP_PATH.'index.php?m=member&c=index&a=login');
  		}
 	}
	
	/**
	 * 我的清单   
	 * eddy
	 */
	public function lists() {
		$member_model = pc_base::load_model('member_model');
		$memberinfo = $member_model->get_one(array('userid' => $this->userid));

		$order_model = pc_base::load_model('order_model');
		$content_total = $order_model->count('`userid`='.$this->userid);
		$page = isset($_GET['page']) && intval($_GET['page']) ? intval($_GET['page']) : 1;
		$pagesize = 12;
		$offset = ($page - 1) * $pagesize;
		
		$order_pages = pages($content_total, $page, $pagesize);
		$order_data = $order_model->select('`userid`='.$this->userid, '*', $offset.",".$pagesize, 'selected DESC, updatetime DESC');
		
		$SEO['title'] = '我的清单 - 会员中心';
		include template('order', 'order');
	}
	
	/**
	 * 更新
	 */
	public function update()
	{
		$in = array_merge($_GET, $_POST);
		$in = new_addslashes($in);
	
		if (!isset($in['id'])) {
			$this->output(false, '参数不正确！');
		}
		$id = intval($in['id']);
		
		if ($in['dosubmit'] == 1) {
			$order_title = htmlspecialchars(trim($in['title']));
			if(empty($order_title)) {
				$this->output(false, '请输入清单标题！');
			}
			if($this->order->count("`title`='".$order_title."' AND `id`!=".$id) > 0) {
				$this->output(false, '您已经存在同名的清单标题！');
			}
			
			$data = array(
				'userid'	=> $this->userid,
				'title'		=> $order_title,
				'selected'	=> (isset($in['selected']) && $in['selected']>0) ? 1 : 0,
				'note'		=> htmlspecialchars(trim($in['note'])),
				'inputtime'	=> time()
			);
			
			if($this->order->update($data, array('id'=>$id))) {
				if($data['selected'] == 1) {
					//更新首选清单
					$this->order->update(array('selected' => 0), '`userid`='.$this->userid. ' AND `id`!='.$id);
				}
				$this->output(true, '编辑清单成功！');
			} else $this->output(false, '编辑清单失败！');
		} else {
			$order = $this->order->get_one(array('id' => $id));
			include template('order','update');
		}
	}
	
	/**
	 * 删除
	 */
	public function delete()
	{
		$in = new_addslashes(array_merge($_GET, $_POST));
		if (isset($in['id']) && intval($in['id'])) {
			$id = intval($in['id']);
			$order = $this->order->get_one(array('id'=>$id));
			if ($this->userid != $order['userid']) {
				$this->output(false, '抱歉，您没有权限删除此清单！');
			}
			if ($order && $this->order->delete(array('id'=>$id))) {
				//删除清单详情
				$order_detail_model = pc_base::load_model('order_detail_model');
				$order_detail_model->delete(array('oid'=>$order['oid']));
				
				//重置首选清单
				if($order['selected'] == 1) {
					$orders = $this->order->select(array('userid'=>$order['userid']), 'id', 1000, 'updatetime DESC');
					if ($orders && !empty($orders)) {
						$this->order->update(array('selected'=>'1'), array('id'=>$orders[0]['id']));
					}
				}
				
			}
			$this->output(true, '删除成功！');
		}
	}
	
	/**
	 * 下载
	 */
	public function download()
	{
		$in = new_addslashes(array_merge($_GET, $_POST));
		if(!class_exists('ZipArchive')) {
			showmessage('该服务器不支持ZIP压缩，请联系网站管理员！', HTTP_REFERER);
		}
		
		if (isset($_GET['id']) && intval($_GET['id'])) {
			$orderid = intval($_GET['id']);
			$order_model = pc_base::load_model('order_model');
			$order = $order_model->get_one(array('id'=>$orderid));
			
			$order_detail_model = pc_base::load_model('order_detail_model');
			$order_detail_data = $order_detail_model->select(array('oid' => $order['oid']));
			
			$CATEGORYS = getcache('category_content_'.get_siteid(),'commons');
			$dirs = array();
			$order_detail_titles = array();
			foreach($order_detail_data AS &$val) {
				if ($val['topcatid'] > 0) {
					//判断是否重名
					if (key_exists($val['producttitle'], $order_detail_titles[$val['topcatid']])) {
						$order_detail_titles[$val['topcatid']][$val['producttitle']]++;
						$val['producttitle'] = '('.$order_detail_titles[$val['topcatid']][$val['producttitle']].')'.$val['producttitle'];
					} else {
						$order_detail_titles[$val['topcatid']][$val['producttitle']] = 1;
					}
				
					if(!in_array($CATEGORYS[$val['topcatid']]['catname'], $dirs)) {
						$dirs[] = $CATEGORYS[$val['topcatid']]['catname'];
					}
					
					if (!empty($CATEGORYS[$val['topcatid']]['catname'])) {
						$val['producttitle'] = $CATEGORYS[$val['topcatid']]['catname'].'/'.$val['producttitle'];
					}
				}
			}
			if (!$order_detail_data) {
				showmessage('您要下载的清单没有添加产品！', HTTP_REFERER);
			}
			
			$year = date('Y', SYS_TIME);
			$month = date('m', SYS_TIME);
			$base_path = realpath(PC_PATH.'../uploadfile/order').'/';
			if (!file_exists($base_path.$year)) {
				@mkdir($base_path.$year, 0775);
			}
			if (!file_exists($base_path.$year.'/'.$month)) {
				@mkdir($base_path.$year.'/'.$month, 0775);
			}
			$path = $base_path.$year.'/'.$month.'/';
			
			//判断是否存在此清单压缩文件，如存在则删除
			$dir = dir($path);
			while (false !== ($entry = $dir->read())) {
			   if (strpos($entry, $order['oid'].'.zip')) {
			   		@unlink($path.$entry);
			   }
			}
			$dir->close();
			
			
			//创建清单压缩文件
			$zip = new ZipArchive();
			$filename = $order['oid'].'.zip';
			if ($zip->open($path.$filename, ZIPARCHIVE::CREATE)!==TRUE) {
			    showmessage('无法生成下载文件，请联系网站管理员！', HTTP_REFERER);
			}
			
			$zip->addEmptyDir(iconv("UTF-8", "GBK", $order['title']));
			
			foreach($dirs as $dir) {
				$zip->addEmptyDir(iconv("UTF-8", "GBK", $order['title'].'/'.$dir));
			}

			foreach ($order_detail_data AS $od) {
				$source = $od['thumb'];
				$localname = explode('/', $source);
				$localname = $localname[count($localname)-1];
				$localname_ext = substr($localname, strpos($localname, '.'));
				$localname = iconv("UTF-8", "GBK", $order['title'].'/'.$od['producttitle'].$localname_ext);
				$zip->addFile($source, $localname);
			}
			
			$zip->close();
			/**
			sleep(10);  //延迟10秒
			
			//执行下载
			//判断要下载的文件是否存在
			$file_path = $path.$filename;
		    if(!file_exists($path.$filename))
		    {
		    	showmessage('对不起,你要下载的文件不存在！', HTTP_REFERER);
		    }
		
		    $file_size = filesize($file_path);
		    header("Content-type: application/x-zip-compressed");
		    header("Accept-Ranges: bytes");
		    header("Accept-Length: $file_size");
		    header("Content-Disposition: attachment; filename=".$filename);
		    
		    $fp = fopen($file_path,"r");
		    $buffer_size = 1024;
		    $cur_pos = 0;
		    
		    while(!feof($fp)&&$file_size-$cur_pos>$buffer_size)
		    {
		        $buffer = fread($fp,$buffer_size);
		        echo $buffer;
		        $cur_pos += $buffer_size;
		    }
		    
		    $buffer = fread($fp,$file_size-$cur_pos);
		    echo $buffer;
		    fclose($fp);
		    
		    //unlink($file_path);
		     */
			header('Location:'.APP_PATH.'uploadfile/order/'.$year.'/'.$month.'/'.$filename);
		} else {
			showmessage('没有您要下载的清单！', HTTP_REFERER);
		}
	}
	
	/**
	 * 更新备注
	 */
	public function update_note()
	{
		$in = array_merge($_GET, $_POST);
		$in = new_addslashes($in);
	
		if (!isset($in['id']) || !intval($in['id'])) {
			$this->output(false, '参数不正确！');
		}
		$id = intval($in['id']);
		
		if ($in['dosubmit'] == 1) {
			$data = array(
				'note'		=> htmlspecialchars(trim($in['note']))
			);
			
			if($this->order->update($data, array('id'=>$id))) {
				$this->output(true, '编辑清单备注成功！');
			} else $this->output(false, '编辑清单备注失败！');
		} else {
			$order = $this->order->get_one(array('id' => $id));
			include template('order','update_note');
		}
	}
	
 	/**
 	 * 创建清单
 	 * Enter description here ...
 	 */
	public function add() {
		$in = array_merge($_GET, $_POST);
		$in = new_addslashes($in);
		
		if ($in['dosubmit'] == 1) {
			$order_title = htmlspecialchars(trim($in['title']));
			if(empty($order_title)) {
				$this->output(false, '请输入清单标题！');
			}
			if($this->order->count("`title`='".$order_title."'") > 0) {
				$this->output(false, '您已经存在同名的清单标题！');
			}
			
			//如果是第一个清单，默认首选
			if (!$this->order->count('`userid`='.$this->userid)) {
				$in['selected'] = 1;
			}
			
			$data = array(
				'userid'	=> $this->userid,
				'title'		=> $order_title,
				'selected'	=> (isset($in['selected']) && $in['selected']>0) ? 1 : 0,
				'note'		=> htmlspecialchars(trim($in['note'])),
				'inputtime'	=> time()
			);
			
			if($data = $this->order->add($data)) {
				if($data['selected'] == 1) {
					//更新首选清单
					$this->order->update(array('selected' => 0), '`userid`='.$this->userid. ' AND `id`!='.$data['id']);
				}
				$this->output(true, '添加清单成功！');
			} else $this->output(false, '添加清单失败！');
		} else {
			include template('order','add');
		}
	}
	
	/**
	 * 设置首选清单	
	 * Enter description here ...
	 * @param unknown_type $code
	 * @param unknown_type $msg
	 */
	public function setSelected() {
		$id = intval($_GET['id']);
		if ($this->order->count('`userid`='.$this->userid. ' AND `id`='.$id)) {
			$this->order->update(array('selected' => 0), '`userid`='.$this->userid);
			$this->order->update(array('selected' => 1), '`id`='.$id);
		}
	}
	
	/**
	 * 复制给好友
	 */
	public function copy()
	{
		$in = array_merge($_GET, $_POST);
		$in = new_addslashes($in);
		$SEO = seo(get_siteid());
		
		$id = intval($in['id']);
		$order = $this->order->get_one(array('id'=>$id));
		$member_db = pc_base::load_model('member_model');

		if ($in['dosubmit'] == 1) {
			$member = $member_db->get_one(array('username'=>$in['username']), 'userid,username');
			if ($member) {
				//创建清单
				if ($member['userid'] == $this->userid) {
					$this->output(false, '不能复制给自己！');
				}
				$data = array(
					'userid'	=> $member['userid'],
					'title'		=> $order['title'],
					'note'		=> $order['note'],
					'parentid'	=> $this->userid,
					'parentname' => $this->username,
					'parentnickname' => param::get_cookie('_nickname'),
					'selected'	=> 0,
					'inputtime'	=> time(),
				);
				if($data = $this->order->add($data)) {
					//复制清单详细
					$order_detail_db = pc_base::load_model('order_detail_model');
					$order_details = $order_detail_db->select(array('oid'=>$order['oid']));
					foreach ($order_details AS $v) {
						$v['oid'] = $data['oid'];
						$v['ordertitle'] = $data['title'];
						$v['userid'] = $member['userid'];
						$v['username'] = $member['username'];
						$v['inputtime'] = time();
						unset($v['id']);
						$order_detail_db->insert($v);
					}
					
					if (isset($in['sendmail']) && $in['sendmail']) {
						//发送邮件
						pc_base::load_sys_func('mail');
						$date = date('Y-m-d', time());
						$_nickname = param::get_cookie('_nickname');
						$rmessage = <<<str
尊敬的{$in['username']}：
您好！

您的好友（{$_nickname} <{$this->username}>）给转发了新的清单。<a href="http://www.108wo.com/">立即查看</a> 。

本邮件由系统自动发送，请勿回复!
{$SEO['name']}
{$date}
str;
						sendmail($in['username'], '来自108wo的清单转发信息', nl2br($rmessage));
					}
					
					$this->output(true, '操作成功！');
				} else $this->output(false, '操作失败！');
			} else {
				$this->output(false, '不存在此会员！');
			}
		}
		
		//获取最多的转发的会员
		$arruserids = $this->order->select(array('parentid'=>$this->userid), 'userid', 100, 'count(parentid) DESC', 'userid');
		$userids = $members = '';
		if ($arruserids) {
			foreach ($arruserids AS $v) {
				$userids .= $v['userid'].',';
			}
			$userids = rtrim($userids, ',');
			if ($userids) $members = $member_db->select('`userid` IN('.$userids.')', 'userid,username,nickname', '', 'find_in_set(userid,"'.$userids.'")');
		}
		
		include template('order','copy');
	}
	
	protected function output($code, $msg, $url='') {
		$in = array_merge($_GET, $_POST);
		if($in['ajax']) {
			die(json_encode(array('code' => $code, 'msg' => $msg)));
		} else {
			$forward = !empty($url) ? $url : HTTP_REFERER;
			showmessage($msg, $forward);
		}
	}
}
?>